
package utils;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import action.vo.LoginInfo;
import config.Constant;

/**
 * Http与Servlet工具类.
 * 
 * @author calvin
 */
public class WebUtils {

	
	public static String render(HttpServletResponse response,String text, String contentType) {
		try {
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {

		}

		return null;
	}

	/**
	 * 直接输出字符串.
	 */
	public static String renderText(HttpServletResponse response,String text) {
		return render(response,text, "text/plain;charset=UTF-8");
	}

	/**
	 * 直接输出HTML.
	 */
	public static String renderHtml(HttpServletResponse response,String html) {
		return render(response,html, "text/html;charset=UTF-8");
	}

	/**
	 * 直接输出XML.
	 */
	public static String renderXML(HttpServletResponse response,String xml) {
		return render(response,xml, "text/xml;charset=UTF-8");
	}

	public static String renderJson(HttpServletResponse response,String json) {
		return render(response,json, "text/json;charset=UTF-8");
	}
	

	public static String renderJs(HttpServletResponse response,String jsText) {
		return render(response,jsText, "application/x-javascript;charset=utf-8");
	}
	
	public LoginInfo getLoginInfo(HttpServletRequest request) {
		LoginInfo loginInfo = (LoginInfo)request.getSession().getAttribute(Constant.LOGININFO);
		return loginInfo;
	}
	
	
	
	/**
	 * 设置客户端缓存过期时间 Header.
	 */
	public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
		//Http 1.0 header
		response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
		//Http 1.1 header
		response.setHeader("Cache-Control", "max-age=" + expiresSeconds);
	}

	/**
	 * 设置客户端无缓存Header.
	 */
	public static void setNoCacheHeader(HttpServletResponse response) {
		//Http 1.0 header
		response.setDateHeader("Expires", 0);
		//Http 1.1 header
		response.setHeader("Cache-Control", "no-cache");
	}

	/**
	 * 设置LastModified Header.
	 */
	public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
		response.setDateHeader("Last-Modified", lastModifiedDate);
	}
	
	/**
	 * 设置让浏览器弹出下载对话框的Header.
	 * 
	 * @param fileName 下载后的文件名.
	 */
	public static void setDownloadableHeader(HttpServletResponse response, String fileName) {
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	}
	
	/**
	 * 取得带相同前缀的Request Parameters.
	 * 
	 * 返回的结果Parameter名已去除前缀.
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getParametersStartingWith(HttpServletRequest request, String prefix) {
		return org.springframework.web.util.WebUtils.getParametersStartingWith(request, prefix);
	}
}
